<template>
  <el-dialog
    class="public-dialog"
    :title="id ? '编辑' : '新增'"
    width="720"
    :modelValue="modelValue"
    @close="handleClose"
    draggable
    align-center
  >
    <div class="h-[460px]">
      <el-form
        ref="formRef"
        label-position="top"
        label-width="100px"
        :model="formData"
        class="form-components"
        :rules="rules"
      >
        <el-form-item label="物流商" prop="logistics_id">
          <el-select
            v-model="formData.logistics_id"
            placeholder="请选择"
            clearable
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in optionsData['logistics']"
              :key="item.logistics_id"
              :label="item.logistics_name"
              :value="item.logistics_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="	贷款类型" prop="payment_type">
          <el-select
            v-model="formData.payment_type"
            placeholder="请选择"
            clearable
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in optionsData['finance_lfp_payment_type']"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="货款所属期" prop="pay_due_date">
          <el-date-picker
            v-model="formData.pay_due_date"
            type="month"
            placeholder="请选择"
            format="YYYY-MM"
            value-format="YYYY-MM"
          />
        </el-form-item>
        <el-form-item label="币种" prop="pay_currency">
          <el-select
            v-model="formData.pay_currency"
            placeholder="请选择"
            clearable
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in currencyData"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="贷款总额" prop="amount">
          <el-input-number
            v-model="formData.amount"
            :controls="false"
            style="width: 100%"
            placeholder="请输入贷款总额"
          />
        </el-form-item>
        <el-form-item label="期望付款日期" prop="expected_pay_date">
          <el-date-picker
            v-model="formData.expected_pay_date"
            type="date"
            placeholder="请选择日"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="付款主体" prop="pay_main_company_id">
          <el-select
            v-model="formData.pay_main_company_id"
            placeholder="请选择"
            clearable
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in optionsData['finance_lpo_pay_main_company']"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="formData.remark"
            :rows="4"
            type="textarea"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-button">
        <el-button :disabled="loading" @click="handleClose(false)">
          {{ disabled ? "关闭" : "取消" }}
        </el-button>
        <el-button
          v-if="!disabled"
          type="primary"
          :loading="loading"
          @click="handleSave"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { getCurrency } from "@/api/public.js";
import { opAdd, opUpdate, opDetail } from "../../api/index.js";
const props = defineProps({
  id: { type: [Number, String], default: "" },
  modelValue: { type: Boolean, default: false },
  optionsData: { type: Object, default: () => ({}) },
});
const disabled = ref(false);
const { id, optionsData } = toRefs(props);
const formData = reactive({
  logistics_id: null,
  payment_type: null,
  pay_currency: null,
  amount: null,
  expected_pay_date: null,
  pay_main_company_id: null,
  remark: null,
  pay_due_date: null,
});
watch(
  () => props.id,
  (val) => {
    if (val) {
      nextTick(() => {
        getDetail();
      });
    }
  }
);

const emit = defineEmits(["update:modelValue", "refresh", "close"]);
const formRef = ref();

const rules = {
  logistics_id: [
    { required: true, message: "请选择供应商", trigger: "change" },
  ],
  payment_type: [
    { required: true, message: "请选择贷款类型", trigger: "change" },
  ],
  pay_due_date: [
    { required: true, message: "请选择贷款所属期", trigger: "change" },
  ],
  pay_currency: [{ required: true, message: "请选择币种", trigger: "change" }],
  amount: [{ required: true, message: "请输入贷款总额", trigger: "change" }],
  expected_pay_date: [
    { required: true, message: "请选择期望付款日期", trigger: "change" },
  ],
  pay_main_company_id: [
    { required: true, message: "请选择付款主体", trigger: "change" },
  ],
};

const getDetail = async () => {
  try {
    let res = await opDetail({ id: id.value });
    if (res.code !== 200) {
      ElMessage.warning(res.message);
      return;
    }
    let data = res?.data;
    const { amount } = data;
    for (let key in formData) {
      formData[key] = data[key];
    }
    formData.amount = Number(amount || 0);
  } catch (error) {}
};

const currencyData = ref([]);
const currencyList = () => {
  getCurrency({}).then((res) => {
    currencyData.value = res?.data || [];
  });
};
currencyList();
const loading = ref(false);
const handleSave = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true;
        let _api = {
          add: opAdd,
          edit: opUpdate,
        };
        const res = await _api[id.value ? "edit" : "add"]({
          id: id.value ?? undefined,
          ...formData,
        });
        if (res.code !== 200) {
          ElMessage.warning(res.message);
          return;
        }
        ElMessage.success("保存成功");
        handleClose(true);
      } catch (e) {
        if (e?.toString().includes(false)) {
          ElMessage.warning("请检查表单信息");
        }
      } finally {
        loading.value = false;
      }
    }
  });
};
const handleClose = async (refresh) => {
  for (let key in formData) formData[key] = null;
  await nextTick();
  formRef.value.resetFields();
  emit("update:modelValue", false);
  emit("close");
  if (refresh) emit("refresh");
};
</script>
<style lang="scss" scoped></style>
